
import pandas as pd
from collections import defaultdict
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtWidgets import QMainWindow, QApplication, QWidget, QLabel,QMessageBox
import sqlite3


class Student:


    def __init__(self, name, stuid, gender, ethnicity, class_info, major,dorm_building,dorm_num):
        self.name=name
        self._stu_id=stuid
        self.gender = gender
        self.ethnicity = ethnicity
        self.class_info = class_info
        self.major = major
        self.dorm_building = dorm_building
        self.dorm_num = dorm_num
        



class Dormitory:
    def __init__(self, name, capacity, total_rooms, gender):
        self.name = name
        self.capacity = capacity  
        self.total_rooms = total_rooms
        self.gender = gender
        self.rooms = defaultdict(list)  
        

        for room in range(1, total_rooms + 1):
            self.rooms[f"{room:03d}"] = []  

    def allocate_dorms(self):
        try:
            # 连接数据库
            conn = sqlite3.connect('student_management.db')
            cursor = conn.cursor()

            # 获取未分配宿舍的学生
            cursor.execute("SELECT * FROM student_info WHERE dorm_building IS NULL OR dorm_num IS NULL")
            unassigned_students = cursor.fetchall()

            for student in unassigned_students:
                student_id = student[2]  # 学号在第三列
                gender = student[3]     # 性别在第四列

                if gender == '男':
                    dorm = self.male_dorm
                elif gender == '女':
                    dorm = self.female_dorm
                else:
                    continue

                # 分配宿舍
                allocated = False
                for room_num, occupants in dorm.rooms.items():
                    if len(occupants) < dorm.capacity:
                        # 更新数据库
                        cursor.execute("""
                            UPDATE student_info 
                            SET dorm_building = ?, dorm_num = ?
                            WHERE student_id = ?
                        """, (dorm.name, room_num, student_id))
                        dorm.rooms[room_num].append(student_id)
                        allocated = True
                        break

                if not allocated:
                    print(f"警告：无法为学号 {student_id} 的学生分配宿舍（{gender}宿舍已满）")

            # 提交更改并关闭连接
            conn.commit()
            conn.close()
            print("宿舍分配完成！")

        except Exception as e:
            print(f"宿舍分配出错: {str(e)}")
    def change_dorm(self, student_id, new_dorm):
        try:
            conn = sqlite3.connect('student_management.db')
            cursor = conn.cursor()

            # 检查学生是否存在
            cursor.execute("SELECT * FROM student_info WHERE student_id = ?", (student_id,))
            student = cursor.fetchone()
            
            if not student:
                return False, "未找到该学号的学生！"

            # 解析新宿舍信息
            dorm_building, room = new_dorm.split('-') if '-' in new_dorm else (new_dorm, "")

            # 检查目标宿舍是否已满
            cursor.execute("""
                SELECT COUNT(*) 
                FROM student_info 
                WHERE dorm_building = ? AND dorm_num = ?
            """, (dorm_building, room))
            count = cursor.fetchone()[0]
            
            if count >= 4:
                return False, "该宿舍已满，无法分配！"

            # 更新宿舍信息
            cursor.execute("""
                UPDATE student_info 
                SET dorm_building = ?, dorm_num = ?
                WHERE student_id = ?
            """, (dorm_building, room, student_id))
            
            conn.commit()
            conn.close()
            
            return True, f"已成功将学号{student_id}的宿舍修改为{new_dorm}"
            
        except Exception as e:
            return False, f"发生错误:\n{str(e)}"
            
    def del_dorm(self, student_id):
        try:
            conn = sqlite3.connect('student_management.db')
            cursor = conn.cursor()

            # 检查学生是否存在
            cursor.execute("SELECT * FROM student_info WHERE student_id = ?", (student_id,))
            student = cursor.fetchone()
            
            if not student:
                return False, "未找到该学号的学生！"

            # 删除宿舍信息
            cursor.execute("""
                UPDATE student_info 
                SET dorm_building = NULL, dorm_num = NULL
                WHERE student_id = ?
            """, (student_id,))
            
            conn.commit()
            conn.close()
            
            return True, f"已成功为学号{student_id}办理退宿"
            
        except Exception as e:
            return False, f"发生错误:\n{str(e)}"
        


if __name__ == "__main__":

    male_dorm = Dormitory("男1号楼", 4, 150, "男")
    female_dorm = Dormitory("女1号楼", 4, 150, "女")
    

    male_dorm.male_dorm = male_dorm
    male_dorm.female_dorm = female_dorm
    female_dorm.male_dorm = male_dorm
    female_dorm.female_dorm = female_dorm
    

    male_dorm.allocate_dorms("students_information.csv")
                
        
            
            

